package com.dhcc.filter;


import com.dhcc.api.R;
import com.dhcc.jwt.JwtTokenUtil;
import com.dhcc.props.AuthProperties;
import com.dhcc.provider.AuthProvider;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * 鉴权认证
 *
 * @author liuguoting
 */
@Slf4j
@Component
@AllArgsConstructor
public class AuthFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final ObjectMapper objectMapper;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (isSkip(path)) {
            return chain.filter(exchange);
        }
        ServerHttpResponse resp = exchange.getResponse();
        String headerToken = exchange.getRequest().getHeaders().getFirst(AuthProvider.AUTH_KEY);
        String paramToken = exchange.getRequest().getQueryParams().getFirst(AuthProvider.AUTH_KEY);
        if (!StringUtils.hasText(headerToken) && !StringUtils.hasText(paramToken)) {
            return unAuth(resp, "缺失令牌,鉴权失败");
        }
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String auth = StringUtils.hasText(headerToken) ? headerToken : paramToken;
        String token = JwtTokenUtil.getToken(auth);
        try {
            Claims claims = JwtTokenUtil.extractClaims(token);
            String subject = claims.getSubject();
            String authToken = opsForValue.get(subject+"@token");
            if (!StringUtils.hasText(authToken)) {
                return unAuth(resp, "令牌无效,鉴权失败");
            }
            //加入权限校验：判断当前请求路径是否有权访问
            String getAuthList = opsForValue.get(subject + "@auth");
            List<String> authList;
            // 判断获取的接口地址字符串是否为 null 或为空
            if (getAuthList != null && !getAuthList.isEmpty()) {
                // 使用 Jackson 反序列化 JSON 字符串为 List
                ObjectMapper objectMapper = new ObjectMapper();
                authList = objectMapper.readValue(getAuthList, List.class);
            }else {
                // 如果没有获取到数据，返回空列表
                authList = List.of();
            }
            // 检查路径是否在 authList 中
            if (!authList.contains(path)) {
                return unAuth(resp, "未授权,无法访问");
            }
        }catch (Exception e) {
            return unAuth(resp, "登陆状态已失效，请重新登陆！");
        }
        return chain.filter(exchange);
    }

    private boolean isSkip(String path) {
        return AuthProvider.getDefaultSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path))
                || authProperties.getSkipUrl().stream().anyMatch(pattern -> antPathMatcher.match(pattern, path));
    }

    private Mono<Void> unAuth(ServerHttpResponse resp, String msg) {
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String result = "";
        try {
            result = objectMapper.writeValueAsString(R.fail(401,msg));
        } catch (JsonProcessingException e) {
            log.error(e.getMessage(), e);
        }
        DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return -100;
    }

}
